/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package examplesocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author 5m
 */
public class ServerReaderStream extends Thread{
    Socket client;
    BufferedReader lettore;
    Boolean stillRunning;
    Stream thisStream;
    ServerReaderStream(Socket pServer, Stream s)
    {
        try 
        {     
            client = pServer;
            thisStream = s;
            stillRunning=true;
        }
        catch (Exception ex)
        {
            System.err.append(ex.getMessage());
        }
    }
    
    public void serviceStop()
    {
        stillRunning = false;
        try {
            lettore.close();
        } catch (IOException ex) {
            System.err.println("Error while closing ServerReaderStream");
        }
    }
    
    @Override
    public void run()
    {
        try {
            lettore = new BufferedReader(new InputStreamReader(client.getInputStream()));
        } catch (IOException ex) {
            Logger.getLogger(ServerReaderStream.class.getName()).log(Level.SEVERE, null, ex);
        }
        while(stillRunning)
        {
            try 
            {         
                if(lettore.ready())
                {
                    StringBuilder b=new StringBuilder();
                    char t=0;
                    while(lettore.ready())
                    {
                        t=(char)lettore.read();
                        if(t==(char)4)
                            break;
                        b.append(t);
                    }

                    if(!b.toString().trim().isEmpty())
                    {
                        String msg=b.toString().trim();
                        msg=msg.substring(0, msg.length());
                        System.out.println(">>> " + msg);
                        Parser.getInstance().decodeMessages(msg, thisStream);
                    }
                }
            }
            catch (IOException ex) 
            {
                System.err.append(ex.getMessage());
            }
        }
    }
}
